package com.wj.facedetect.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.wj.facedetect.R;
import com.wj.facedetect.activity.alarm.AlarmDetailActivity;
import com.wj.facedetect.activity.alarm.MyTaskActivity;
import com.wj.facedetect.bean.alarm.GetAlarmListBean;
import com.wj.facedetect.net.ReqUrls;
import com.wj.facedetect.presenter.AlarmPresenter;
import com.wj.facedetect.util.PreferencesUtils;
import com.wj.facedetect.util.TimeUtils;
import com.wj.facedetect.util.ToastUtil;
import com.wj.facedetect.view.IBaseView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AlarmFragment extends Fragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, IBaseView {

    private View mainView;
    private RecyclerView recyclerView;
    private AlarmAdapter adapter;
    private CanRefreshLayout canRefreshLayout;
    private AlarmPresenter alarmPresenter;
    private int pageNo = 1, pageSize = 5;
    private List<GetAlarmListBean.DataBean.ListBean> list = new ArrayList<>();
    private TextView tvRight;
    private AlarmPushBroadcastReceiver alarmPushBroadcastReceiver;
    private static final int REQ_GET_ALARMLIST = 0x001;

    public AlarmFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (alarmPushBroadcastReceiver == null) {
            alarmPushBroadcastReceiver = new AlarmPushBroadcastReceiver();
        }
        IntentFilter intentFilter = new IntentFilter("com.wj.facedetect.AlarmPushFlash");
        getActivity().registerReceiver(alarmPushBroadcastReceiver, intentFilter);
        mainView = inflater.inflate(R.layout.fragment_alarm, container, false);
        alarmPresenter = new AlarmPresenter(this);
        initView();
        return mainView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (alarmPushBroadcastReceiver != null) {
            getActivity().unregisterReceiver(alarmPushBroadcastReceiver);
        }
    }

    private void initView() {
        canRefreshLayout = mainView.findViewById(R.id.refresh);
        recyclerView = mainView.findViewById(R.id.can_content_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        adapter = new AlarmAdapter();
        recyclerView.setAdapter(adapter);
        canRefreshLayout.setOnLoadMoreListener(this);
        canRefreshLayout.setOnRefreshListener(this);
        canRefreshLayout.autoRefresh();
        tvRight = mainView.findViewById(R.id.tv_right);
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MyTaskActivity.class);
                getActivity().startActivity(intent);
            }
        });
    }

    @Override
    public void onLoadMore() {
        pageNo = pageNo + 1;
        canRefreshLayout.setRefreshEnabled(false);
        requestData();
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        canRefreshLayout.setLoadMoreEnabled(false);
        requestData();
    }


    public void requestData() {
        alarmPresenter.doRequestGetAlarmList(pageNo + "", pageSize + "", REQ_GET_ALARMLIST, this);
    }

    @Override
    public void onSuccess(int what, Object data, Object carryObj) {
        if (canRefreshLayout != null) {
            canRefreshLayout.refreshComplete();
            canRefreshLayout.loadMoreComplete();
            canRefreshLayout.setLoadMoreEnabled(true);
            canRefreshLayout.setRefreshEnabled(true);
        }
        if (what == REQ_GET_ALARMLIST) {
            GetAlarmListBean getAlarmListBean = (GetAlarmListBean) data;
            if (getAlarmListBean != null) {
                if (getAlarmListBean.isSuccess()) {
                    GetAlarmListBean.DataBean dataBean = getAlarmListBean.getData();
                    if (dataBean != null) {
                        if (pageNo == 1) {
                            list = dataBean.getList();
                        } else {
                            list.addAll(dataBean.getList());
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    public void onError(int what, Exception e, Object carryObj) {
        if (canRefreshLayout != null) {
            canRefreshLayout.refreshComplete();
            canRefreshLayout.loadMoreComplete();
            canRefreshLayout.setLoadMoreEnabled(true);
            canRefreshLayout.setRefreshEnabled(true);
        }
        ToastUtil.showMessage("网络异常");
    }

    @Override
    public void onFail(int what, int errorCode, String errorMsg, Object carryObj) {
        if (canRefreshLayout != null) {
            canRefreshLayout.refreshComplete();
            canRefreshLayout.loadMoreComplete();
            canRefreshLayout.setLoadMoreEnabled(true);
            canRefreshLayout.setRefreshEnabled(true);
        }
    }

    class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.MyViewHolder> {
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.alarm_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            final GetAlarmListBean.DataBean.ListBean listBean = list.get(position);
            if (!TextUtils.isEmpty(listBean.getAcquiredFaceImg())) {
                String photoUrl1Temp = listBean.getAcquiredFaceImg().replace("\n", "");
                holder.headView.setImageURI(PreferencesUtils.getInstance().getSharePreStrBaseUrl(PreferencesUtils.BASE_URL)
                        + String.format(ReqUrls.URL_GET_PHOTO2, listBean.getClusterId(), photoUrl1Temp));
            }
            if (!TextUtils.isEmpty(listBean.getPersonName())) {
                holder.tvXyfName.setText(listBean.getPersonName());
            }
            if (!TextUtils.isEmpty(listBean.getAddr())) {
                holder.tvAddr.setText(listBean.getAddr());
            }
            BigDecimal b = listBean.getHitPrecent();
            if (b != null) {
                double ppd = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                holder.tvSim.setText(ppd + "");
            }
            long time = listBean.getTime();
            long timeLong = time * 1000;
            String formatTimeByType = TimeUtils.getFormatTimeByType(timeLong, TimeUtils.DATE_FORMAT_MMDDHHMM);
            holder.tvTime.setText(formatTimeByType);
            holder.tvKuName.setText(listBean.getRepositoryName());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), AlarmDetailActivity.class);
                    intent.putExtra("message", listBean.getId() + "");
                    intent.putExtra("tag", "alarm");
                    getActivity().startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            private SimpleDraweeView headView;
            private TextView tvKuName, tvSim, tvAddr, tvXyfName, tvTime;

            public MyViewHolder(View itemView) {
                super(itemView);
                headView = itemView.findViewById(R.id.iv_head_1);
                tvKuName = itemView.findViewById(R.id.tv_ku_name);
                tvSim = itemView.findViewById(R.id.tv_sim);
                tvAddr = itemView.findViewById(R.id.tv_addr);
                tvXyfName = itemView.findViewById(R.id.tv_xyf_name);
                tvTime = itemView.findViewById(R.id.tv_time);
            }
        }
    }

    class AlarmPushBroadcastReceiver extends BroadcastReceiver {
        public String TAG = AlarmPushBroadcastReceiver.class.getName();

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "received in AlarmreflashDataBroadcastReceiver");
            if (canRefreshLayout != null) {
                canRefreshLayout.autoRefresh();
            }
        }
    }

}
